//
//  SosSetViewController.m
//  Lightthings
//
//  Created by 王岩 on 2024/12/6.
//

#import "SosSetViewController.h"

@interface SosSetViewController ()
/* <#note#> */
@property (nonatomic, strong) MainSectionModel * s;
@end

@implementation SosSetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.jy_title = SWString(@"SOS设置");
    
    self.tableInsets =  kEdge(self.jy_bar_h, 0, klSafeAreaEdgeInsets.bottom + 70, 0);
    
    [self.rightBtn setImage:U_imageNamed(@"添加＋") forState:0];
    self.rightBtn.zh_action = kMsgForward(@"addAction", WKProxy(self));
    
    NSString * uuid = self.metaInfo[@"uuid"];
    NSArray * list = [FRQBluetoothManager shareManager].curPeripherals;
    for (CBPeripheral * per in list) {
        if ([per.identifier.UUIDString isEqualToString:uuid]) {
            self.peripheral = per;
        }
    }
    
    [self readData];
    
    _s = [[MainSectionModel alloc] init];

    self.dataSources  = @[_s];
    
    // Do any additional setup after loading the view.
}

- (void)readData {
    [WatchCommandTool.sharedInstance writeStormCommand:Command_SOS ToPeripheral:self.peripheral Value:nil reBack:^(NSString * _Nonnull backData) {
        if (backData) {
            NSString * value = [backData substringFromIndex:26];
            if (value.length > 4) {
                NSString * phoneString = [value substringWithRange:NSMakeRange(4, 40)];
                NSString * nameString = [value substringFromIndex:44];
                
                [self.s.items addObject:[self cModelWithPhone:phoneString Name:[nameString substringToIndex:nameString.length - 2]]];
                [self reloadIfNeeded];
            }
        }
    }];
}

- (void)addNewSOS:(NSString *)name Phone:(NSString *)phone {
 
    NSMutableArray * arr = [[NSMutableArray alloc] init];
    arr[0] = @(0);
    arr[1] = @(0);
    
    for (int i = 0; i < 20; i ++) {
        if (i < phone.length) {
            [arr addObject:@([self intFromDataReverse:[[phone substringWithRange:NSMakeRange(i, 1)] dataUsingEncoding:NSUTF8StringEncoding]])];
        }else {
            [arr addObject:@(0)];
        }
    }
  /// %E6%88%91%E6%98%AF
    NSString * string = [name stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSArray * stringarr = [string componentsSeparatedByString:@"%"];
    for (int i = 0; i < stringarr.count; i ++) {
        NSString * str = [stringarr objectAtIndex:i];
        if (str.length > 0) {
            NSInteger value = strtoll([[NSString stringWithFormat:@"0x%@",str] UTF8String], 0, 16);
            [arr addObject:@(value)];
        }
    }
    NSLog(@"写入SOS name= %@, phone =%@", name ,phone);
    [[WatchCommandTool sharedInstance] writeStormCommand:Command_SOS ToPeripheral:self.peripheral Value:arr reBack:^(NSString * _Nonnull backData) {
        if (backData) {
            if ([backData hasSuffix:@"00"]) {
                NSString * value = [backData substringFromIndex:26];
                NSString * phoneString = [value substringWithRange:NSMakeRange(4, 40)];
                NSString * nameString = [value substringFromIndex:44];
                
                [self.s.items addObject:[self cModelWithPhone:phoneString Name:[nameString substringToIndex:nameString.length - 2]]];
                [self reloadIfNeeded];
                toast(SWString(@"Success"));
            }else {
                toast(SWString(@""));
            }
//            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
    
}

- (TitleModel *)cModelWithPhone:(NSString *)phonestr Name:(NSString *)nameStr {
    
    NSMutableArray * phone = [[NSMutableArray alloc] init];
    for (int i = 0 ; i < phonestr.length / 2; i ++) {
        NSString * substr = [phonestr substringWithRange:NSMakeRange(i * 2, 2)];
        if ([substr isEqualToString:@"00"]) {
            continue;
        }
        unsigned long  value2 = strtoll([[NSString stringWithFormat:@"0x%@",substr] UTF8String], 0, 16);
        NSData * data = [NSData dataWithBytes:&value2 length:sizeof(value2)];
        NSString * str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        [phone addObject:[NSString stringWithFormat:@"%d", str.intValue]];
    }
    NSMutableArray * name = [[NSMutableArray alloc] init];
    for (int i = 0; i < nameStr.length / 2; i ++) {
        NSString * substr = [nameStr substringWithRange:NSMakeRange(i * 2, 2)];
        [name addObject:[NSString stringWithFormat:@"%%%@",substr]];
    }
     
    TitleModel * m = [TitleModel cModelT:[[name componentsJoinedByString:@""] stringByRemovingPercentEncoding] DetailS:[phone componentsJoinedByString:@""] s:CGSizeMake(kScreenWidth, 55)];
    m.idfBlock = ^NSString * _Nonnull{
        return @"SOSViewCell";
    };
    return m;
}

- (int) intFromDataReverse:(NSData *)data
{
    int intSize = sizeof(int);// change it to fixe length
    unsigned char * buffer = malloc(intSize * sizeof(unsigned char));
    [data getBytes:buffer length:intSize];
    int num = 0;
    for (int i = intSize - 1; i >= 0; i--) {
        num = (num << 8) + buffer[i];
    }
    free(buffer);
    return num;
}

- (void)addAction {
    __block UITextField *tf = nil;
    __block UITextField *tf2 = nil;
    [LEEAlert alert].config
    .LeeTitle(SWString(@"请输入联系人"))
    .LeeAddTextField(^(UITextField *textField) {
        // 这里可以进行自定义的设置
        textField.placeholder = SWString(@"请输入姓名");
        if (@available(iOS 13.0, *)) {
            textField.textColor = [UIColor secondaryLabelColor];
        } else {
            textField.textColor = [UIColor darkGrayColor];
        }
        textField.keyboardType = UIKeyboardTypeDefault;
        tf = textField; //赋值
    }) 
    .LeeAddTextField(^(UITextField *textField) {
        // 这里可以进行自定义的设置
        textField.placeholder = SWString(@"请输入电话");
        if (@available(iOS 13.0, *)) {
            textField.textColor = [UIColor secondaryLabelColor];
        } else {
            textField.textColor = [UIColor darkGrayColor];
        }
        textField.keyboardType = UIKeyboardTypeNumberPad;
        tf2 = textField; //赋值
    })
    .LeeAction(SWString(@"确定"), ^{
        [self addNewSOS:tf.text Phone:tf2.text];
    })
    .leeShouldActionClickClose(^(NSInteger index){
        // 是否可以关闭回调, 当即将关闭时会被调用 根据返回值决定是否执行关闭处理
        // 这里演示了与输入框非空校验结合的例子
        BOOL result = ![tf.text isEqualToString:@""];
        BOOL result2 = ![tf2.text isEqualToString:@""];
        result = index == 0 ? result : YES;
        result2 = index == 0 ? result2 : YES;
        BOOL r = result && result2;
        return r;
    })
    .LeeCancelAction(SWString(@"取消"), nil) // 点击事件的Block如果不需要可以传nil
    .LeeShow();
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
